/*
 * Basic no frills app which integrates the ZBar barcode scanner with
 * the camera.
 * 
 * Created by lisah0 on 2012-02-24
 */
package com.bingkaimedia.dompetobeta.app;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import com.bingkaimedia.dompetobeta.R;
import com.bingkaimedia.dompetobeta.app.CameraPreview;
import com.bingkaimedia.dompetobeta.libs.JSONfunctions;
import com.bingkaimedia.dompetobeta.libs.LazyAdapter2;
import com.bingkaimedia.dompetobeta.libs.SessionManager;
import com.bingkaimedia.dompetobeta.libs_image.ImageLoader;
import com.bingkaimedia.dompetobeta.libs_slidemenu.BaseActivity;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.Intents.Insert;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;

import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;

import android.widget.TextView;
import android.graphics.ImageFormat;

/* Import ZBar Class files */
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.Config;

@SuppressLint("NewApi")
public class My_Voucher_QRcode extends BaseActivity  {
  
	// XML node keys 
	//static final String KEY_SONG = "song"; // parent node
	
	public static String FOR_ID_TRANSACTION = "";
	
	public static final String KEY_VOUCHER_ID = "voucher_id";
	public static final String KEY_VOUCHER_NAME = "voucher_name"; 
	public static final String KEY_VOUCHER_TOTAL = "voucher_total";
	public static final String KEY_VOUCHER_TERSEDIA = "voucher_tersedia";
	public static final String KEY_VOUCHER_DETAIL = "voucher_detail";
	public static final String KEY_VOUCHER_DATE = "voucher_date";
	public static final String KEY_VOUCHER_DESCRIPTION = "voucher_description";
	public static final String KEY_MERCHANT_ID = "merchant_id";
	public static final String KEY_MERCHANT_NAME = "merchant_name";
	public static final String KEY_MERCHANT_CATEGORY = "merchant_category";
	public static final String KEY_MERCHANT_PHOTO = "merchant_photo";
	public static final String KEY_TRANSACTION_ID = "transaction_id";
	public static final String KEY_TRANSACTION_DATE = "transaction_date";
	public static final String KEY_TRANSACTION_IMAGE = "transaction_image";
	public static final String KEY_TRANSACTION_STATUS = "transaction_status";
	
	public static final String KEY_MY_CHANNEL_ID = "my_channel_id";
	public static final String KEY_CHANNEL_ID = "channel_id";
	public static final String KEY_USERS_ID = "users_id";
	public static final String KEY_CHANNEL_NAME = "channel_name";
	public static final String KEY_CHANNEL_ADDRESS = "channel_address";
	public static final String KEY_CHANNEL_PHOTO = "channel_photo";
	public static final String KEY_CHANNEL_NOTE = "channel_note";
	
	private String xml_voucher_id;
	private String xml_voucher_name;
	private String xml_voucher_total;
	private String xml_voucher_tersedia;
	private String xml_voucher_description;
	private String xml_voucher_detail;
	private String xml_voucher_date;
	private String xml_merchant_id;
	private String xml_merchant_name;
	private String xml_merchant_category;
	private String xml_merchant_photo;
	private String xml_transaction_id;
	private String xml_transaction_date;
	private String xml_transaction_image;
	private String xml_transaction_status;
	

	private String xml_my_channel_id;
	private String xml_channel_id;
	private String xml_users_id;
	private String xml_channel_name;
	private String xml_channel_photo;
	private String xml_channel_note;
	private String xml_channel_address;
	
	private String session_userid;
	private String session_username;
	private String session_password;
	private String session_email;
	private String session_city;
	private String session_checked;
	private String session_channel;
	private String session_category;
    
	
	public My_Voucher_QRcode() {
		super(R.string.baru);  
		}
	
	int current_page = 0;
    
    public ImageLoader imageLoader; 
    
    private String idtransaksi;

	private ArrayList<City_Array> citylist;
	final List<String> list = new ArrayList<String>();
	private SlidingMenu sm;
	
 // Session Manager Class
 	SessionManager session;
 	
 	LazyAdapter2 adapter;
 	ArrayList<HashMap<String, String>> menuItems;
 	ProgressDialog pDialog;
 	HashMap<String, String> map = new HashMap<String, String>();
 	
 	ArrayList<HashMap<String, String>> diskonba_list = new ArrayList<HashMap<String, String>>();
 	 
 	//slide menu
 	private LinearLayout slidingPanel;
 	private boolean isExpanded;
 	private DisplayMetrics metrics;
 	private RelativeLayout headerPanel;
 	private int panelWidth;
 	private int panelWidth1;

 	private String sta="";
 	private String id_;
 	ArrayList nameValuePairs;
	String result = null;
	InputStream is = null;
	StringBuilder sb=null;
	ImageLoader imgLoader;
	String tanggal1,tanggal2;
 	private ImageView menuViewButton,menuRightButton;

 	FrameLayout.LayoutParams menuPanelParameters;
 	FrameLayout.LayoutParams slidingPanelParameters;
 	LinearLayout.LayoutParams headerPanelParameters;
 	LinearLayout.LayoutParams listViewParameters;
 	

 	private CharSequence[] value={"Bandung", "Jakarta"};
	
 	private EditText txt_city;
	private Button send;
	private Button cancel;
	
 
    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;

    int endfor = 0;
    TextView scanText;
    TextView scanText2;
    Button scanButton;
    Button absen;

    //String url_insert = "http://192.168.2.27/absensi_andro/insert.php?";
    String url_insert = Global.link_my_voucher_use;
    ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;

 
    static {
        System.loadLibrary("iconv");
    } 
    
    

    
    @Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
    
    
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.my_voucher_qrcode);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);

        
        fungsi_menu(); 
		
		nameValuePairs = new ArrayList();
		
		imgLoader = new ImageLoader(getApplicationContext());
		
		session = new SessionManager(getApplicationContext());
	    
	    HashMap<String, String> user = session.getUserDetails();
	     
	    // name
	    session_userid = user.get(SessionManager.id_users);
	    session_username = user.get(SessionManager.username);
	    session_password = user.get(SessionManager.password);
	    session_email = user.get(SessionManager.email);
	    session_city = user.get(SessionManager.city);
	    session_checked = user.get(SessionManager.checked);
	    session_channel = user.get(SessionManager.channel);
	    session_category = user.get(SessionManager.category);
		
	 // getting intent data
        Intent in = getIntent();
         
        // Get XML values from previous intent
        id_ = in.getStringExtra(KEY_CHANNEL_ID);
        //String title_ = in.getStringExtra(KEY_MERCHANT_NAME);
        //String artist_ = in.getStringExtra(KEY_VOUCHER_NAME);
        //String duration_ = in.getStringExtra(KEY_VOUCHER_TOTAL);
        //String thumb_url_ = in.getStringExtra(KEY_MERCHANT_PHOTO);
        
       // new loadListView().execute();
         
        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);
        
        scanText = (TextView)findViewById(R.id.scanText);
        scanText2 = (TextView)findViewById(R.id.scanText2);
        
        scanText.setVisibility(0);
        scanText2.setVisibility(0);
        scanButton = (Button)findViewById(R.id.ScanButton);
       // absen = (Button)findViewById(R.id.absen);
        
        scanText2.setText(FOR_ID_TRANSACTION);
        
        scanButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (barcodeScanned) {
                    barcodeScanned = false;
                    scanText.setText("Scanning..."); 
                      
						mCamera.setPreviewCallback(previewCb);

	                    mCamera.startPreview();
	                    
	                    endfor=0;
                    previewing = true;
                    mCamera.autoFocus(autoFocusCB);
                }
            }
        });
       
        /*
        absen.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	new Check().execute();
            }
        });
        */
    }
    
    public void fungsi_menu(){
		
		setSlidingActionBarEnabled(true);
		 
        sm = getSlidingMenu();
		 
		LinearLayout header_vertical_divider_1 = (LinearLayout) findViewById(R.id.header_vertical_divider_1);
		LinearLayout header_vertical_divider_2 = (LinearLayout) findViewById(R.id.header_vertical_divider_2);
		ImageView diskonion_iconmenu = (ImageView) findViewById(R.id.diskonion_iconmenu);
		ImageView diskonion_iconhome = (ImageView) findViewById(R.id.diskonion_iconhome);
		ImageView diskonion_iconsearch = (ImageView) findViewById(R.id.diskonion_iconsearch);
		ImageView diskonion_iconcategory = (ImageView) findViewById(R.id.diskonion_iconcategory);
		
		 
		
		diskonion_iconmenu.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showMenu(); 
			}
		}); 
		
		diskonion_iconhome.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Home.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconsearch.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Search.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconcategory.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showSecondaryMenu(); 
			}
		});
 		
	}

    public void onPause() {
        super.onPause();
        //releaseCamera();
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            //mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
            public void run() {
                if (previewing)
                    mCamera.autoFocus(autoFocusCB);
            }
        };

    PreviewCallback previewCb = new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);

                

                if (result != 0) {
                	
                	previewing = false;
                    mCamera.setPreviewCallback(null);
                    mCamera.stopPreview();
                    mCamera.lock();
                    
                    SymbolSet syms = scanner.getResults();
                    //System.out.println("symbol");
                    //System.out.println(syms.toString());
                    for (Symbol sym : syms) {
                        scanText.setText(sym.getData());
                        barcodeScanned = true;
                        endfor = endfor + 1;
                        //System.out.println("endfor " + endfor);
                    }
                    
                      
                    if(endfor == 1)
                    {
                    	AlertDialog.Builder builder=new AlertDialog.Builder(My_Voucher_QRcode.this);
        				builder.setTitle("Use voucher")
        				.setMessage("Are you sure want to use this voucher ?")
        				.setPositiveButton("Yes",new DialogInterface.OnClickListener()
        				{
        						public void onClick(DialogInterface dialog,int id)
        						{
        							new Check().execute();
        							
        							//Intent intent=new Intent(getApplicationContext(),Home.class);
        		    				//startActivity(intent);
        		    				//List_Data_Detail.this.finish();
        						}
        				  }) 
        				  .setNegativeButton("No",new DialogInterface.OnClickListener()
        				  {
        						public void onClick(DialogInterface dialog,int id) 
        						{
        							  
        						}
        				  })
        				  .show();	
        				endfor=0;
                    }
                }
                
                
            }
        };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
                autoFocusHandler.postDelayed(doAutoFocus, 1000);
            }
        };

 
	

	
	class Check extends AsyncTask {

		private String json;
		private JSONObject jsonobject;
		private String code;
		private String msg;
		public String url;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			url = Global.link_my_voucher_use + scanText2.getText() + "&qrcode=" + scanText.getText();
			 
			url = url.replace("+", "%20");
			url = url.replace(" ", "%20"); 
			url = url.replace("#", "~"); 
			//System.out.println(url);

			pDialog = new ProgressDialog(
					My_Voucher_QRcode.this);
			pDialog.setMessage("Retrieve Data, Please wait...");
			pDialog.setIndeterminate(true);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Object doInBackground(Object... params) {
			code="99";
			msg="Not connected to server";
			
			try {
				json = JSONfunctions.getStringContent(url);
				jsonobject = new JSONObject(json);
				code = jsonobject.getString("code");
				//code = "1";
				msg = jsonobject.getString("msg");
				//Toast.makeText(getApplicationContext(), "Mohon Tunggu",
				//		30000).show();
				
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("catch code msg");
				System.out.println(e);
				Toast.makeText(getBaseContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			if (code.equalsIgnoreCase("1")) {
				
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(My_Voucher_QRcode.this); 
	            alertDialog.setTitle("Notification"); 
	            alertDialog.setMessage(msg); 
	            alertDialog.setIcon(R.drawable.image_success); 
	            alertDialog.setPositiveButton("OK",
	                    new DialogInterface.OnClickListener() {
	                        public void onClick(DialogInterface dialog,int which) {
	                            // Write your code here to execute after dialog
	                        	Intent i = new Intent(getApplicationContext(), My_Voucher.class);
	                            startActivity(i); 
	                            finish();
	                        }
	                    });
	            

	            // Showing Alert Message
	            alertDialog.show();
				//Toast.makeText(My_Voucher_QRcode.this, "Voucher has been used.",
				//		Toast.LENGTH_LONG).show();
				   
			} else {
				//Toast.makeText(My_Voucher_QRcode.this, "Voucher cannot use.",
				//		Toast.LENGTH_LONG).show();
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(My_Voucher_QRcode.this); 
	            alertDialog.setTitle("Notification"); 
	            alertDialog.setMessage(msg); 
	            alertDialog.setIcon(R.drawable.image_fail); 
	            alertDialog.setPositiveButton("OK",
	                    new DialogInterface.OnClickListener() {
	                        public void onClick(DialogInterface dialog,int which) {
	                            // Write your code here to execute after dialog
	                        	Intent i = new Intent(getApplicationContext(), My_Voucher.class);
	                            startActivity(i); 
	                            finish();
	                        }
	                    });
	            

	            // Showing Alert Message
	            alertDialog.show();
			}
		}

	}
	
	
}
